<template>
  <div class="log-item">
    <div class="main">
      <div class="user">
        <xr-avatar
          v-if="data.createUser"
          :id="data.createUser.userId"
          :name="data.createUser.realname"
          :size="32"
          :src="data.createUser.img"
          :disabled="false"
          class="user-img" />
        <div class="box">
          <div>
            <div class="username">
              {{ data.createUser.realname }}<span class="dept">{{ data.createUser.deptName }}</span>
            </div>
            <div class="time">
              {{ data.createTime }}<span class="tag">创建了新日志</span><!--{{ data.isRead === 1 ? '已读' : '未读' }}-->
            </div>
            <el-button
              v-if="showHistoryBtn"
              style="padding: 10px 0;"
              type="link"
              @click="checkHistoryClick">查看以往日志</el-button>
          </div>
          <div
            class="handle">
            <el-dropdown
              v-if="data.permission && (data.permission.isUpdate || data.permission.isDelete)"
              trigger="click"
              @command="handleCommand">
              <el-button
                icon="el-icon-more"
                class="more" />
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-if="data.permission.isUpdate"
                  command="edit">编辑</el-dropdown-item>
                <el-dropdown-item
                  v-if="data.permission.isDelete"
                  command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <!-- <div class="comment-status">
            <span class="icon wk wk-task" />
            <span>{{ getCategory(data.categoryId) }}-{{ data.replyNum === 0 ? '未点评' : '已点评' }}</span>
            <span :class="{active: data.replyNum !== 0}" class="dot" />
          </div> -->
        </div>
      </div>
      <div class="content is-cursor-pointer" style="margin-top: 8px;" @click="$emit('detail')">
        <log-fields-view
          :fields="data.fieldList.filter(o => !['createUserName', 'createTime'].includes(o.fieldName))"
        />

        <div
          v-if="data.printContent"
          class="file-item"
          @click.stop>
          <img
            :src="require('@/assets/img/file/file_word.png')"
            alt=""
            class="pic-icon">
          <div class="file-name text-one-line">{{ data.templateName }}</div>
          <div class="down">
            <el-button type="primary-text" @click="previewFileClick('perview')">预览</el-button>
            <el-button type="primary-text" @click="previewFileClick('download')">下载</el-button>
          </div>
        </div>
      </div>

      <picture-list-view
        v-if="data.img && data.img.length !== 0"
        :list="data.img" />

      <!-- <file-list-view
        v-if="data.file && data.file.length !== 0"
        :list="data.file" /> -->
      <div
        v-if="data.file && data.file.length !== 0"
        class="content"
        style="margin-left: 45px;">
        <div class="content-box">
          <div class="content-title">
            附件
          </div>
          <file-cell :file-list="data.file" />
        </div>
      </div>

      <flexbox v-if="showSendUserList.length > 0" class="send-list">
        <span class="send-list__label">发送给：</span>
        <!-- <span
          v-for="(item, sendIndex) in (data.sendUserList || []).concat(data.sendDeptList || [])"
          :key="sendIndex"
          class="send-list__user">
          <xr-avatar
            :name="item.realname || item.name"
            :size="32"
            :src="item.img" />
        </span> -->
        <el-tooltip
          v-for="(item, userIndex) in showSendUserList"
          :key="userIndex"
          :class="{'is-close': allSendUserDeptList.length > maxSendShowCount}"
          placement="top"
          :content="item.realname || item.name"
          class="send-user">
          <xr-avatar
            :id="item.userId"
            :name="item.realname || item.name"
            :size="32"
            :disabled="!item.userId"
            :src="item.img" />
        </el-tooltip>
        <el-dropdown
          v-if="allSendUserDeptList.length > maxSendShowCount"
          trigger="click"
          :hide-on-click="false">
          <el-button class="dropdown-btn">
            +{{ allSendUserDeptList.length - maxSendShowCount }}
          </el-button>
          <el-dropdown-menu slot="dropdown" class="send-list-dropdown">
            <el-dropdown-item
              v-for="(userItem, userIndex) in closeSendUserDeptList"
              :key="userIndex"
              class="send-list-dropdown-list">
              <p class="send-list-dropdown-text">{{ userItem.realname || userItem.name }} </p>
              <!-- <i
                  class="el-icon-close send-list-dropdown-i"
                  @click="deleteSendList(item, index + 5)" /> -->
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </flexbox>
    </div>

    <div class="footer">
      <el-button
        type="icon"
        icon="wk wk-message"
        class="replay-btn"
        @click="replayClick">{{ (replyTotal > 0 ? `${replyTotal}` : '评论') }}</el-button>
      <div style="flex: 1;">
        <fav-list
          :is-favour="data.isFavour"
          :data="data.favourUser"
          @fav="favourClick"
        />
      </div>
      <!-- <el-button
        ref="favBtn"
        :type="data.isFavour ? 'primary' : ''"
        style="margin-left: 10px;"
        icon="wk wk-good"
        class="fav-btn"
        @click="favourClick">赞{{ `${data.favourUser.length > 0 ? `(${data.favourUser.length})` : ''}` }}</el-button> -->
    </div>
    <div
      v-if="showReply"
      class="reply-wrapper-wrap">
      <div
        class="reply-wrapper">
        <flexbox align="stretch" class="reply-comment-wrap">
          <xr-avatar
            :name="userInfo.realname"
            :size="32"
            :src="userInfo.img"
            class="user-img" />
          <reply-comment
            ref="f_reply"
            v-loading="commentLoading"
            :props="{
              contentType: commentListProps.contentType
            }"
            @toggle="closeOtherReply"
            @reply="handleReply" />
        </flexbox>
        <comment-list
          v-if="replyList.length > 0"
          ref="comment_list"
          :props="commentListProps"
          :list="replyList"
          @delete="deleteComment"
          @close-other-reply="$refs.f_reply.toggleFocus(true)" />
      </div>
    </div>
  </div>
</template>

<script>
// API
import {
  journalDeleteAPI,
  journalSetReadAPI,
  oaLogFavourOrCancelAPI
} from '@/api/oa/journal'
import {
  setCommentAPI,
  deleteCommentAPI,
  queryCommentListAPI
} from '@/api/oa/common'
import {
  oaLogPrintTemplatePreviewAPI,
  oaLogPrintTemplateDownAPI
} from '@/api/admin/oa'
import { downloadFileAPI } from '@/api/common'

import PictureListView from '@/components/PictureListView'
import ReplyComment from '@/components/ReplyComment'
import FileCell from '@/components/FileCell'
import CommentList from '@/components/CommentList'
import FavList from './FavList'
import LogFieldsView from './LogFieldsView'

import { mapGetters } from 'vuex'
import { downloadFileWithBuffer } from '@/utils'

export default {
  name: 'LogItem',
  components: {
    PictureListView,
    CommentList,
    ReplyComment,
    FavList,
    FileCell,
    LogFieldsView
  },
  props: {
    data: {
      type: Object,
      required: true
    },
    index: {
      type: Number,
      default: 0
    },
    showHistoryBtn: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isWaiting: false,
      showReply: false,
      commentLoading: false,
      replyList: [],
      maxSendShowCount: 5
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    replyTotal() {
      let num = 0
      this.replyList.forEach(item => {
        num++
        num += item.childCommentList.length || 0
      })
      return num || this.data.replyNum
    },

    // 评论列表配置
    commentListProps() {
      return {
        addRequest: setCommentAPI, // 添加请求和参数
        addParams: {
          titleName: '',
          typeId: this.data?.logId || '',
          type: '2'
        }, // 3 知识库 2 日志 1 任务
        replyKey: 'pid', // 日志 任务 pid  阶段 replyId
        replyValueKey: 'userId', // 获取值的keys 日志 任务 userId  阶段 user.userId
        deleteRequest: deleteCommentAPI, // 删除请求和参数
        deleteParams: null,
        contentType: 'rich'
      }
    },

    // 展示的发送人
    showSendUserList() {
      return this.allSendUserDeptList.slice(0, this.maxSendShowCount)
    },

    // 全部发送人
    allSendUserDeptList() {
      const defaultSendUserList = (this.data.sendUserList || []).map(item => {
        item.disabled = true
        return item
      })
      const defaultSendDeptList = (this.data.sendDeptList || []).map(item => {
        item.disabled = true
        return item
      })

      return defaultSendUserList.concat(defaultSendDeptList)
    },

    // 闭合起来的员工和部门
    closeSendUserDeptList() {
      return this.allSendUserDeptList.slice(this.maxSendShowCount)
    }

  },
  created() {
    // this.$nextTick(() => {
    //   if (this.data.isRead === 1) return
    //   this.$bus.on('load-more-work-log', clientHeight => {
    //     if (this.isWaiting) return
    //     if (this.calcVisible(clientHeight)) {
    //       this.isWaiting = true
    //       setTimeout(() => {
    //         this.isWaiting = false
    //         if (this.calcVisible(clientHeight)) {
    //           this.readLog()
    //         }
    //       }, 3000)
    //     }
    //   })
    // })

  },
  beforeDestroy() {
    // this.$bus.off('load-more-work-log')
  },
  methods: {
    getCategory(categoryId) {
      const map = {
        1: '日报',
        2: '周报',
        3: '月报'
      }
      return map[categoryId]
    },
    /**
     * 编辑/删除
     * @param action
     * @param index
     */
    handleCommand(action, index) {
      if (action === 'delete') {
        this.$confirm('确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          journalDeleteAPI({ logId: this.data.logId }).then(() => {
            this.$message.success('删除成功!')
            this.$emit('delete', index)
          })
        }).catch(() => {
        })
      } else {
        this.$emit('edit', this.index, this.data)
      }
    },

    /**
     * 判断当前组件是否完全可见
     */
    calcVisible(boxHeight) {
      if (this.data.isRead === 1) return false
      const domRect = this.$el.getBoundingClientRect()
      return boxHeight > (domRect.top + domRect.height)
    },

    /**
     * 日志标记为已读
     */
    readLog() {
      if (this.data.isRead === 1) return
      this.$emit('read')
      journalSetReadAPI({
        logId: this.data.logId
      }).then(() => {
        this.$bus.off('load-more-work-log')
      }).catch()
    },

    /**
     * 日志评论
     */
    handleReply(data, atList) {
      this.commentLoading = true
      setCommentAPI({
        content: data,
        atUserId: (atList || []).map(item => item.userId),
        pid: this.data.createUserId,
        ...this.commentListProps.addParams
      }).then(res => {
        res.data.user = {
          userId: this.userInfo.userId,
          realname: this.userInfo.realname,
          img: this.userInfo.img
        }
        res.data.childCommentList = []
        // this.$emit('add-comment', {
        //   data: res.data,
        //   index: this.index
        // })
        this.replyList.push(res.data)
        this.commentLoading = false
        this.showReply = false
        this.$nextTick(() => {
          this.showReply = true
        })
      }).catch(() => {
        this.commentLoading = false
      })
    },

    deleteComment(index) {
      this.replyList.splice(index, 1)
    },

    closeOtherReply(flag) {
      if (!flag && this.$refs.comment_list) {
        this.$refs.comment_list.closeReply()
      }
    },

    /**
     * 回复点击
     */
    replayClick() {
      this.showReply = !this.showReply
      if (this.replyList.length == 0) {
        this.getCommentList()
      }
    },

    /**
     * 获取回复列表
     */
    getCommentList() {
      queryCommentListAPI({
        typeId: this.data.logId,
        type: 2 // 任务1 日志2
      })
        .then(res => {
          const list = res.data || []
          this.replyList = list
          // this.replyList = list.sort((a, b) => {
          //   return new Date(b.createTime) - new Date(a.createTime)
          // }) || []
        })
        .catch(() => {})
    },

    /**
     * 简报详情
     */
    reportSelect(item) {
      this.$emit('report-detail', item, this.data)
    },

    /**
     * 查看历史
     */
    checkHistoryClick() {
      this.$emit('check-history', this.data.createUser)
    },

    /**
     * 点赞
     *
     */
    favourClick() {
      oaLogFavourOrCancelAPI({
        isFavour: !this.data.isFavour,
        logId: this.data.logId
      }).then(res => {
        const resData = res.data || {}
        this.data.isFavour = resData.isFavour
        this.data.favourUser = resData.favourUser
      })
        .catch(() => {})
    },

    /**
     * @description: 预览附件的预览和下载
     * @return {*}
     */
    previewFileClick(type) {
      this.loading = true
      oaLogPrintTemplatePreviewAPI({
        type: 'word',
        content: this.data.printContent
      })
        .then(res => {
          this.loading = false
          const resData = res.data
          if (type === 'download') {
            var data = {
              key: resData,
              type: 2 // word
            }
            oaLogPrintTemplateDownAPI(data).then(res => {
              downloadFileWithBuffer(res.data, '预览文档.doc')
            }).catch(() => {})
          } else {
            const iframeUrl = `/oaLogPrintTemplate/preview.pdf?type=1&key=${resData}`

            downloadFileAPI(iframeUrl).then(res => {
              window.open(window.URL.createObjectURL(res.data), '_blank')
            }).catch(() => {})
          }
        })
        .catch(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style scoped lang="scss">
.log-item {
  .main {
    .user {
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      font-size: 14px;

      .user-img {
        margin-right: 12px;
      }

      .box {
        display: flex;
        flex: 1;
        align-items: center;
        justify-content: space-between;

        .username {
          .dept {
            margin-left: $--interval-base * 2;
            color: $--color-text-secondary;
          }
        }

        .time {
          margin-top: 2px;
          color: $--color-text-secondary;

          .tag {
            margin-left: $--interval-base;
          }
        }

        .handle {
          margin-left: 24px;

          .more {
            margin-left: $--interval-base;
          }
        }

        .comment-status {
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;

          .icon {
            margin-right: 5px;
            font-size: 14px;
            color: #2772ff;
          }

          .dot {
            display: inline-block;
            width: 7px;
            height: 7px;
            margin-left: 5px;
            background-color: #f95a5a;
            border-radius: 50%;

            &.active {
              background-color: #4ca824;
            }
          }
        }
      }
    }

    .content {
      margin: 0 0 0 45px;

      &.is-cursor-pointer {
        cursor: pointer;
      }

      .content-box {
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 16px;
        }

        .content-title {
          margin-bottom: $--interval-base;
          font-weight: bold;
          color: $--color-text-secondary;
        }

        .content-text {
          line-height: 1.5;
          word-wrap: break-word;
          white-space: pre-wrap;
        }
      }

      // 背景风格
      &.is-background {
        padding: $--interval-base;
        background-color: $--color-n10;
        border-radius: $--border-radius-base;

        .content-box {
          margin-bottom: 0;
        }
      }
    }

    .picture-list-view {
      margin: 0 15px 10px 45px;
    }

    .file-list-view {
      width: 800px;
      margin: 0 15px 10px 45px;
    }

    .related-business-list {
      width: 800px;
      margin: 0 15px 10px 45px;
    }
  }

  .footer {
    display: flex;
    align-items: center;
    width: 100%;
    height: 38px;
    padding: 0 16px;
    padding-left: 45px;
    margin-top: $--interval-base;
    border-radius: $--border-radius-base;

    .fav-btn,
    .replay-btn {
      padding-left: 0;
    }
  }

  .reply-wrapper-wrap {
    padding-left: 40px;
    margin-top: $--interval-base;
  }

  .reply-wrapper {
    padding: 20px 20px 10px;
    border: $--border-base;
    border-radius: $--border-radius-base;
  }

  .reply-comment-wrap {
    .user-img {
      margin-top: 5px;
      margin-right: $--interval-base;
    }

    .reply-comment {
      flex: 1;
    }
  }

  .comment-list {
    margin-top: #{$--interval-base * 2};
  }
}

// 发送人
.send-user {
  position: relative;
  display: inline-block;

  &.is-close {
    border: 3px solid #fff;
    border-radius: 50%;
  }

  &.is-close + &.is-close {
    margin-left: -13px !important;
  }
}

.send-user + .send-user {
  margin-left: 7px;
}

.send-list-dropdown {
  width: 200px;
  max-height: 300px;
  overflow-y: auto;

  &-list {
    position: relative;
    display: flex;
    align-items: center;
    padding-top: 5px;
    padding-bottom: 5px;
    border-left: 2px solid $--color-white;

    &:hover {
      background: $--color-n20 !important;
      border-left: 2px solid $--color-b400;
    }

    &:hover .send-list-dropdown-i {
      display: inline-block;
      color: $--color-n500;
    }

    &:hover .send-list-dropdown-text {
      color: $--color-n500;
    }
  }

  &-text {
    display: inline-block;
    width: 80px;
    height: 32px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &-i {
    position: absolute;
    top: 18px;
    right: 10px;
    display: none;
    margin-left: 60px;
  }
}

.send-list {
  padding: 8px 15px 8px 45px;

  &__label {
    color: $--color-n200;
  }

  // &__user {
  //   position: relative;
  //   display: inline-block;
  // }

  // &__user + &__user {
  //   margin-left: 7px;
  // }
}

.section {
  padding: 10px 0;

  &__hd {
    span {
      font-weight: $--font-weight-semibold;
    }
  }

  &__bd {
    margin-top: #{$--interval-base * 2};
  }

  ::v-deep &-add {
    width: 32px;
    height: 32px;
    line-height: 32px;
    color: $--color-n800;
    text-align: center;
    cursor: pointer;
    border-radius: $--border-radius-base;
    transform: translateY(-25%);

    &:hover {
      background-color: $--color-n20;
    }
  }
}

.affix-all {
  margin-right: 1px;
  margin-bottom: 30px;
  margin-left: 1px;
  border-radius: 4px;
  box-shadow: $--box-shadow-bottom-light;

  &:hover {
    box-shadow: $--box-shadow-hover-bottom-light;
  }
}

.file-item {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  margin-bottom: 8px;
  line-height: 1.5;

  .pic-icon {
    flex-shrink: 0;
    width: 12px;
    margin-right: 8px;
  }

  .file-name {
    margin-right: 18px;
  }

  .down {
    flex-shrink: 0;
  }
}
</style>
